package makabakaquestionnaire.zutsoftware.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import makabakaquestionnaire.zutsoftware.constant.Result;
import makabakaquestionnaire.zutsoftware.entity.UserProject;
import makabakaquestionnaire.zutsoftware.entity.Users;
import makabakaquestionnaire.zutsoftware.framework.security.Service.AuthLoginService;
import makabakaquestionnaire.zutsoftware.framework.security.model.LoginBody;
import makabakaquestionnaire.zutsoftware.framework.security.utils.SecurityUtils;
import makabakaquestionnaire.zutsoftware.mapper.UsersMapper;
import makabakaquestionnaire.zutsoftware.service.IUsersService;
import makabakaquestionnaire.zutsoftware.system.common.AjaxResult;
import makabakaquestionnaire.zutsoftware.system.entity.SysMenu;
import makabakaquestionnaire.zutsoftware.system.service.ISysMenuService;
import makabakaquestionnaire.zutsoftware.utils.DateUtils;
import makabakaquestionnaire.zutsoftware.utils.workWx.HttpClientUtil;
import makabakaquestionnaire.zutsoftware.utils.workWx.WorkWXAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Api(tags = "用户接口")
@RestController
public class UserLoginController {

    @Autowired
    UsersMapper usersMapper;
    @Autowired
    AuthLoginService authLoginService;
    @Autowired
    IUsersService usersService;
    @Autowired
    private ISysMenuService menuService;

    @RequestMapping("/getByName/{name}")
    public String getByName(@PathVariable String name) {
        return usersMapper.queryByName(name).toString();
    }

    @ApiOperation("获取用户信息")
    @RequestMapping("/getById/{Id}")
    public Result getById(@ApiParam("用户Id") @PathVariable Long Id) {
        return Result.success(usersMapper.selectUsersById(Id));
    }
//@RequestParam(name = "state") String state
    @GetMapping("/wxLogin")
    public Result WxLogin(@RequestParam(name = "code") String code ) {
        /**
         * 获得企业微信登陆的access_token,指定token的类型即可
         */
        Map<String, Object> wxResponse = HttpClientUtil.wxRequest("Login_SECRET",
                String.format(WorkWXAPI.GET_LOGINID_URL, "Login_SECRET", code), null, HttpClientUtil.METHOD_GET);
        /**
         * 设置数据库中用户名唯一
         * 两种方案
         * 1.根据用户名去查数据库，查不到登录失败
         * 2.根据用户名去查数据库，查不到创建user  √    再进行jwt校验
         */
        String userName = wxResponse.get("UserId").toString();
        Users users = usersService.selectUsersByName(userName);
        if (users == null) {
            Map<String, Object> userInfo = HttpClientUtil.wxRequest("SECRET",
                    String.format(WorkWXAPI.GET_USERINFO_URL, "SECRET", userName), null, HttpClientUtil.METHOD_GET);
            users = new Users();
            users.setEmail(userInfo.get("email").toString());
            users.setUserName(userInfo.get("userid").toString());
            users.setAvater(userInfo.get("thumb_avatar").toString());
            String gender = userInfo.get("gender").toString();
            if (gender.equals("1")) {
                users.setSex("男");
            } else {
                users.setSex("女");
            }
            users.setIphone(userInfo.get("mobile").toString());
            users.setPassword("123");
            users.setStatus(userInfo.get("status").toString());
            users.setCreateTime(DateUtils.getNowDate());
            users.setLastLoginTime(DateUtils.getNowDate());
            usersService.insertUsers(users);
        } else {
            users.setLastLoginTime(DateUtils.getNowDate());
            usersService.updateUsers(users);
        }
        String token = authLoginService.login0(users.getUserName(), users.getPassword());
        return Result.success(token);
    }

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     */
    @PostMapping("/doLogin")
    public Result login(@RequestBody LoginBody loginBody) {
        //鉴权，成功返回token
        String token = authLoginService.login(loginBody.getUsername(),
                loginBody.getPassword(), loginBody.getCode(), loginBody.getUuid());
        return Result.success(token);
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("/getMenus")
    public AjaxResult getMenus() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenusVo(menus));
    }


}

